import "handsontable/dist/handsontable.full.css";
import React from "react";
import { useState, useRef, useEffect } from "react";
import { HotTable } from "@handsontable/react";
import { useForm } from "react-hook-form";
import { ipcRenderer } from "electron";
import {
  checkUserName,
  checkID,
  checkPhone,
  extendObj,
  insertUser,
  sleep,
} from "../assets/utils";
import { cp } from "original-fs";
function row2obj(row_obj, reverse = false) {
  //  序号	社区	姓名	电话	身份证号	用户名	密码	政治面貌	已处理吗	用户名已占用	电话已占用	身份证已占用	注册错误
  const maps = [
    "series",
    "community",
    "name",
    "telephone",
    "idnumber",
    "username",
    "password",
    "politicalStatus",
    "isworked",
    "usernameerror",
    "telerror",
    "idnumbererror",
    "registererror",
  ];
  if (reverse) {
    const row = maps.map((k) => row_obj[k]);
    return row;
  } else {
    const obj = Object.fromEntries(maps.map((k, i) => [k, row_obj[i]]));
    return obj;
  }
}
function Table() {
  const tableRef = useRef();
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  const onSubmit = (data) => {
    console.log(data);
    work(tableRef, Number(data.maxInsert));
  };
  const [settings, setSettings] = useState({
    data: [
      ["序号", "社区", "姓名", "电话", "身份证号", "用户名", "密码"],
      ["1", "泉塘社区", 11, 12, 13],
      ["2", "泉塘社区", 11, 14, 13],
      ["3", "泉塘社区", 15, 12, 100],
    ],
  });
  useEffect(() => {
    ipcRenderer.on("save-action", () => {
      const data = tableRef.current.hotInstance.getData();
      ipcRenderer.send("save-data", data);
    });
    ipcRenderer.on("load-action", (e, csvarray) => {
      console.log(csvarray);
      setSettings(Object.assign({}, settings, { data: csvarray }));
    });
  }, []);
  return (
    <div id="hot-app">
      <button
        onClick={() => {
          setSettings(
            Object.assign({}, settings, {
              minRows: tableRef.current.hotInstance.countRows() + 10,
            })
          );
        }}
      >
        add 10 rows
      </button>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input
          type="number"
          {...register("maxInsert", { required: true, min: 0 })}
        ></input>
        {errors.maxInsert && <span>必须是数字且大于0</span>}
        <button type="submit">设置最大插入量并开始</button>
      </form>
      <HotTable
        ref={tableRef}
        settings={settings}
        licenseKey="non-commercial-and-evaluation"
      />
    </div>
  );
}
async function work(tableRef, maxInsert) {
  let initInsert = 0;
  const hot = tableRef.current.hotInstance;
  const hotData = hot.getData(); // array
  for (let i = 1; i < hot.countRows(); i++) {
    await sleep(3000);
    const obj = row2obj(hotData[i]);
    console.log(obj);
    let insertObj;
    try {
      insertObj = extendObj(obj);
    } catch (e) {
      console.log(`covert ${JSON.stringify(obj)} error!`);
      continue;
    }
    if (!obj.isworked || obj.isworked.includes("否")) {
      // 已处理吗 是 空 或者 是 否
      let cUsername = await checkUserName(insertObj.userName);
      console.log(`cUsername: ${cUsername}`);
      obj.usernameerror = cUsername == 1 ? "" : "已使用";
      sleep(500);
      let cPhone = await checkPhone(insertObj.mobile);
      console.log(`cPhone: ${cPhone}`);
      obj.telerror = cPhone == 1 ? "" : "已使用";
      sleep(500);
      let cID = await checkID(insertObj.idcardCode);
      console.log(`cID: ${cID}`);
      obj.idnumbererror = cID == 1 ? "" : "已使用";
      sleep(500);
      if (cUsername == 1 && cPhone == 1 && cID == 1) {
        const result = await insertUser(insertObj);
        sleep(1000);
        obj.registererror = result == 1 ? "无错误" : JSON.stringify(result);
        obj.username = insertObj.userName;
        obj.password = insertObj.userPassword;
        obj.isworked = "是";
        ++initInsert;
      }
    }
    row2obj(obj, true).map((k, col) => {
      console.log(k, col);
      hot.setDataAtCell(i, col, k);
    });
    if (initInsert >= maxInsert) {
      break;
    }
  }
}
export default Table;
